<template>
  <view class="album-detail-container">
    <!-- 专辑标题和描述 -->
    <view class="album-header">
      <view class="album-title">{{ album.title || '我的专辑' }}</view>
      <view class="album-description">{{ album.description || '暂无描述' }}</view>
    </view>
    
    <!-- 作者信息 -->
    <view class="author-info" @click="navigateToProfile(album.user && album.user.id)">
      <image class="author-avatar" :src="(album.user && album.user.avatar) || '/static/images/default-avatar.png'" mode="aspectFill"></image>
      <view class="author-detail">
        <text class="author-name">{{ (album.user && album.user.nickname) || (album.user && album.user.username) || '未知用户' }}</text>
      </view>
      <view class="follow-btn" v-if="!isCurrentUser && album.user && album.user.id">
        <follow-button :user-id="album.user.id"></follow-button>
      </view>
    </view>
    
    <!-- 专辑图片网格 -->
    <view class="album-grid">
      <view 
        class="album-image-item" 
        v-for="(image, index) in album.images" 
        :key="index"
        @click="previewImage(image.url, index)"
      >
        <image :src="image.url" mode="aspectFill"></image>
      </view>
    </view>
    
    <!-- 创建时间 -->
    <view class="create-time">
      创建于 {{ formatDateTimeStr(album.createTime) }}
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn share-btn" @click="shareAlbum">
        <text class="btn-icon">🔗</text>
        <text class="btn-text">分享专辑</text>
      </button>
    </view>
    
    <!-- 互动区域 -->
    <view class="interaction-area">
      <view class="like-btn" @click="likeAlbum">
        <text class="iconfont icon-like" :class="{ active: album.isLiked }">❤️</text>
        <text class="count">{{ album.likeCount }}</text>
      </view>
      <view class="comment-btn">
        <text class="iconfont icon-comment">💬</text>
        <text class="count">{{ album.commentCount }}</text>
      </view>
    </view>
    
    <!-- 评论区域 -->
    <view class="comments-area">
      <view class="comments-header">
        <text class="comments-title">评论 ({{ comments.length }})</text>
        <text class="sort-btn">最新</text>
      </view>
      
      <!-- 评论列表 -->
      <view class="comments-list">
        <view class="comment-item" v-for="(comment, index) in comments" :key="index">
          <view class="comment-header">
            <view class="comment-user" @click="navigateToProfile(comment.userId)">
              <image class="user-avatar" :src="comment.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
              <text class="user-name">{{ comment.username }}</text>
            </view>
            <text class="comment-time">{{ formatRelativeTimeStr(comment.createTime) }}</text>
          </view>
          <view class="comment-content">
            {{ comment.content }}
          </view>
        </view>
        <view class="no-comment" v-if="comments.length === 0">
          <text>暂无评论，快来发表第一条评论吧</text>
        </view>
      </view>
      
      <!-- 评论输入框 -->
      <view class="comment-input">
        <input 
          type="text" 
          v-model="commentText" 
          placeholder="写下你的评论..." 
          confirm-type="send"
          @confirm="submitComment"
        />
        <button class="send-btn" @click="submitComment">发送</button>
      </view>
    </view>
    
    <!-- 相似专辑推荐 -->
    <view class="similar-albums">
      <view class="similar-title">相似专辑推荐</view>
      <scroll-view scroll-x class="similar-list">
        <view 
          class="similar-item" 
          v-for="(item, index) in similarAlbums" 
          :key="index"
          @click="goToAlbumDetail(item.id)"
        >
          <view class="similar-cover">
            <image :src="item.coverImage" mode="aspectFill"></image>
            <view class="image-count">{{ item.imageCount }}张</view>
          </view>
          <view class="similar-info">
            <text class="similar-album-title">{{ item.title }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import * as commonUtils from '@/utils/common.js';
import api from '@/utils/api.js';
import FollowButton from '@/components/user/FollowButton.vue';

export default {
  components: {
    FollowButton
  },
  data() {
    return {
      // 专辑ID
      albumId: null,
      // 评论文本
      commentText: '',
      // 加载状态
      loading: {
        album: false,
        comments: false,
        similarAlbums: false
      },
      
      // 专辑信息
      album: {
        id: null,
        title: '',
        description: '',
        coverImage: '',
        images: [],
        createTime: '',
        user: {
          id: null,
          username: '',
          nickname: '',
          avatar: ''
        },
        likeCount: 0,
        commentCount: 0,
        isLiked: false
      },
      
      // 评论列表
      comments: [],
      
      // 相似专辑推荐
      similarAlbums: [],
      
      // 是否为当前用户
      isCurrentUser: false
    }
  },
  
  onLoad(options) {
    console.log('专辑详情页面接收到的参数：', options);
    if (options.id) {
      this.albumId = parseInt(options.id);
      this.loadAlbumDetail();
      this.loadComments();
      this.loadSimilarAlbums();
    }
  },
  
  methods: {
    // 格式化日期时间
    formatDateTimeStr(time) {
      return commonUtils.formatDateTime(time);
    },
    
    // 格式化相对时间
    formatRelativeTimeStr(time) {
      return commonUtils.formatRelativeTime(time);
    },
    
    // 加载专辑详情
    async loadAlbumDetail() {
      if (this.loading.album) return;
      
      try {
        this.loading.album = true;
        
        // 调用真实API
        const res = await api.album.getAlbumDetail(this.albumId);
        
        if (res && res.code === 200 && res.data) {
          // 处理images字段，确保格式正确
          let images = [];
          if (res.data.images) {
            // 如果images是字符串数组，转换为对象数组
            if (Array.isArray(res.data.images) && typeof res.data.images[0] === 'string') {
              images = res.data.images.map(url => ({ url }));
            } else {
              // 如果已经是对象数组，直接使用
              images = res.data.images;
            }
          }
          
          // 格式化数据
          this.album = {
            id: res.data.id,
            title: res.data.title || '未命名专辑',
            description: res.data.description || '',
            coverImage: res.data.coverImage || (images.length > 0 ? (images[0].url || images[0]) : ''),
            images: images,
            createTime: res.data.createTime || new Date().toISOString(),
            user: res.data.creator || res.data.user || {},
            likeCount: res.data.likeCount || 0,
            commentCount: res.data.commentCount || 0,
            isLiked: res.data.isLiked || false
          };
          
          // 检查是否为当前用户
          const currentUser = await api.user.getUserInfo();
          if (currentUser.code === 200 && currentUser.data) {
            this.isCurrentUser = currentUser.data.id === this.album.user?.id;
          }
        } else {
          uni.showToast({
            title: res?.message || '获取专辑详情失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取专辑详情失败:', error);
        uni.showToast({
          title: '获取专辑详情失败，请检查网络',
          icon: 'none'
        });
      } finally {
        this.loading.album = false;
      }
    },
    
    // 加载评论列表
    async loadComments() {
      if (!this.albumId || this.loading.comments) return;
      
      try {
        this.loading.comments = true;
        
        // 调用真实API
        const res = await api.album.getComments(this.albumId, { page: 1, size: 20 });
        
        if (res && res.code === 200 && res.data) {
          // 格式化评论数据
          this.comments = (res.data.list || []).map(item => ({
            id: item.id,
            albumId: this.albumId,
            userId: item.userId || item.user?.id,
            username: item.username || item.user?.nickname || item.user?.username || '匿名用户',
            avatar: item.avatar || item.user?.avatar || '/static/images/default-avatar.png',
            content: item.content || '',
            createTime: item.createTime || new Date().toISOString()
          }));
        } else {
          console.warn('获取评论失败:', res?.message);
          this.comments = [];
        }
      } catch (error) {
        console.error('获取评论失败:', error);
        this.comments = [];
      } finally {
        this.loading.comments = false;
      }
    },
    
    // 加载相似专辑推荐
    async loadSimilarAlbums() {
      if (!this.albumId || this.loading.similarAlbums) return;
      
      try {
        this.loading.similarAlbums = true;
        
        // 这里应该调用获取相似专辑的API
        // 目前后端可能没有此API，使用获取公开专辑的API替代
        const res = await api.album.getAlbumList({ page: 1, size: 5 });
        
        if (res && res.code === 200 && res.data) {
          // 过滤掉当前专辑
          const albums = (res.data.list || []).filter(item => item.id !== this.albumId);
          
          // 格式化数据
          this.similarAlbums = albums.map(item => ({
            id: item.id,
            title: item.title || '未命名专辑',
            coverImage: item.coverImage || (item.images && item.images.length > 0 ? item.images[0] : ''),
            imageCount: item.imageCount || (item.images ? item.images.length : 0)
          }));
        } else {
          console.warn('获取相似专辑失败:', res?.message);
          this.similarAlbums = [];
        }
      } catch (error) {
        console.error('获取相似专辑失败:', error);
        this.similarAlbums = [];
      } finally {
        this.loading.similarAlbums = false;
      }
    },
    
    // 预览图片
    previewImage(url, currentIndex) {
      const urls = this.album.images.map(img => img.url);
      uni.previewImage({
        urls: urls,
        current: currentIndex
      });
    },
    
    // 分享专辑
    shareAlbum() {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      });
      
      // 实际项目中可以实现分享功能
      // api.album.shareAlbum({ albumId: this.album.id })
      //   .then(res => {
      //     // 处理分享结果
      //   })
      //   .catch(err => {
      //     console.error('分享失败:', err);
      //   });
    },
    
    // 点赞专辑
    likeAlbum() {
      if (!this.album.id) return;
      
      // 乐观更新UI
      const originalLikeStatus = this.album.isLiked;
      const originalLikeCount = this.album.likeCount;
      
      // 先更新UI状态
      if (this.album.isLiked) {
        this.album.likeCount--;
      } else {
        this.album.likeCount++;
      }
      this.album.isLiked = !this.album.isLiked;
      
      // 调用API
      api.album.interact({
        targetId: this.album.id,
        type: 'like'
      }).catch(err => {
        console.error('点赞失败:', err);
        // 恢复原状态
        this.album.isLiked = originalLikeStatus;
        this.album.likeCount = originalLikeCount;
        
        uni.showToast({
          title: '点赞失败，请稍后再试',
          icon: 'none'
        });
      });
    },
    
    // 提交评论
    submitComment() {
      if (!this.commentText.trim()) {
        uni.showToast({
          title: '评论内容不能为空',
          icon: 'none'
        });
        return;
      }
      
      if (!this.album.id) {
        uni.showToast({
          title: '专辑信息加载中，请稍后再试',
          icon: 'none'
        });
        return;
      }
      
      // 创建临时评论对象（乐观UI更新）
      const tempComment = {
        id: Date.now(), // 临时ID
        albumId: this.album.id,
        userId: 1,
        username: '我',
        avatar: '/static/images/default-avatar.png',
        content: this.commentText,
        createTime: new Date().toISOString()
      };
      
      // 先添加到列表
      this.comments.unshift(tempComment);
      this.album.commentCount++;
      
      // 清空输入框
      const commentText = this.commentText;
      this.commentText = '';
      
      // 调用API
      api.album.interact({
        targetId: this.album.id,
        type: 'comment',
        content: commentText
      })
        .then(res => {
          if (res && res.code === 200) {
            // 更新临时评论的ID
            if (res.data && res.data.id) {
              const index = this.comments.findIndex(c => c.id === tempComment.id);
              if (index !== -1) {
                this.comments[index].id = res.data.id;
              }
            }
            
            uni.showToast({
              title: '评论成功',
              icon: 'success'
            });
          } else {
            throw new Error(res?.message || '评论失败');
          }
        })
        .catch(err => {
          console.error('评论失败:', err);
          
          // 从列表中移除临时评论
          const index = this.comments.findIndex(c => c.id === tempComment.id);
          if (index !== -1) {
            this.comments.splice(index, 1);
          }
          
          // 恢复评论数
          this.album.commentCount--;
          
          // 恢复评论文本
          this.commentText = commentText;
          
          uni.showToast({
            title: '评论失败，请稍后重试',
            icon: 'none'
          });
        });
    },
    
    // 跳转到专辑详情
    goToAlbumDetail(id) {
      // 如果是当前专辑，不跳转
      if (id === this.albumId) return;
      
      uni.navigateTo({
        url: `/pages/album-detail/album-detail?id=${id}`
      });
    },
    
    // 跳转到用户主页
    navigateToProfile(userId) {
      if (!userId) {
        console.warn('用户ID不存在，无法跳转到个人主页');
        return;
      }
      
      console.log('跳转到用户主页：', userId);
      
      uni.navigateTo({
        url: `/pages/user/profile?id=${userId}`
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.album-detail-container {
  padding-bottom: 100rpx;
}

/* 专辑标题和描述 */
.album-header {
  padding: 30rpx;
  background-color: #fff;
}

.album-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.album-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

/* 作者信息 */
.author-info {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  
  .author-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
  }
  
  .author-detail {
    flex: 1;
    
    .author-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 4rpx;
    }
    
    .publish-time {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .follow-btn {
    margin-left: 20rpx;
  }
}

/* 专辑图片网格 */
.album-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 10rpx;
  background-color: #fff;
}

.album-image-item {
  width: calc(33.33% - 20rpx);
  margin: 10rpx;
  position: relative;
  
  &::before {
    content: "";
    display: block;
    padding-top: 100%; /* 保持1:1的宽高比 */
  }
  
  image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
    object-fit: cover;
  }
}

/* 创建时间 */
.create-time {
  padding: 20rpx 30rpx;
  font-size: 24rpx;
  color: #999;
  text-align: right;
  background-color: #fff;
}

/* 操作按钮 */
.action-buttons {
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.action-btn {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  border-radius: 12rpx;
}

.share-btn {
  background-color: #FF69B4;
  color: #fff;
}

.btn-icon {
  font-size: 40rpx;
  margin-right: 10rpx;
}

.btn-text {
  font-size: 28rpx;
}

/* 互动区域 */
.interaction-area {
  display: flex;
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.like-btn, .comment-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
}

.iconfont {
  margin-right: 10rpx;
  font-size: 36rpx;
}

.iconfont.active {
  color: #FF69B4;
}

.count {
  font-size: 28rpx;
}

/* 评论区域 */
.comments-area {
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.comments-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.sort-btn {
  font-size: 26rpx;
  color: #999;
}

.comments-list {
  margin-bottom: 30rpx;
}

.comment-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.comment-user {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 16rpx;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.comment-time {
  font-size: 24rpx;
  color: #999;
}

.comment-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

.no-comment {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.comment-input {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
}

.comment-input input {
  flex: 1;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
}

.send-btn {
  margin-left: 20rpx;
  background-color: #FF69B4;
  color: #fff;
  font-size: 28rpx;
  padding: 0 30rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
}

/* 相似专辑推荐 */
.similar-albums {
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.similar-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.similar-list {
  white-space: nowrap;
}

.similar-item {
  display: inline-block;
  width: 250rpx;
  margin-right: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.similar-cover {
  position: relative;
  width: 100%;
  height: 250rpx;
}

.similar-cover image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx 12rpx 0 0;
}

.image-count {
  position: absolute;
  bottom: 10rpx;
  right: 10rpx;
  font-size: 22rpx;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.similar-info {
  padding: 10rpx;
}

.similar-album-title {
  font-size: 26rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
